import 'package:flutter/material.dart';
import 'package:flutter_hplus/components/tables/index.dart';
import 'package:flutter_hplus/theme/theme.dart';

/// 可编辑数据表格页面
/// 
/// 展示可编辑数据表格组件的使用方法和效果
class EditableTablePage extends StatefulWidget {
  /// 构造函数
  const EditableTablePage({super.key});

  @override
  State<EditableTablePage> createState() => _EditableTablePageState();
}

class _EditableTablePageState extends State<EditableTablePage> {
  // 可编辑表格数据
  List<Map<String, dynamic>> _editableData = [
    {'engine': 'Skia', 'platform': 'Android', 'architecture': 'ARM64', 'version': '3.19.0', 'performance': 'A+', 'status': '稳定', 'api': 'OpenGL/Vulkan', 'features': '完全支持Flutter API', 'migration': '无需迁移', 'notes': '默认渲染引擎，性能良好'},
    {'engine': 'Impeller', 'platform': 'iOS', 'architecture': 'ARM64', 'version': '3.29.0', 'performance': 'A+', 'status': '默认', 'api': 'Metal', 'features': '预编译着色器，无运行时编译', 'migration': '强制使用', 'notes': 'Skia已完全移除，部分API可能需要适配'},
    {'engine': 'Impeller', 'platform': 'Android', 'architecture': 'ARM64', 'version': '3.29.0', 'performance': 'A+', 'status': '默认', 'api': 'Vulkan', 'features': '预编译着色器，减少内存使用', 'migration': '默认启用', 'notes': '性能有明显提升'},
  ];
  
  // 表格列定义
  final List<HDataColumn> _columns = [
    const HDataColumn(label: 'Flutter 渲染引擎', field: 'engine', width: 150),
    const HDataColumn(label: '运行平台', field: 'platform', width: 120),
    const HDataColumn(label: 'CPU架构', field: 'architecture', width: 100),
    const HDataColumn(label: '引擎版本', field: 'version', width: 100),
    const HDataColumn(label: '性能', field: 'performance', width: 70), 
    const HDataColumn(label: '支持状态', field: 'status', width: 100),
    const HDataColumn(label: '图形API', field: 'api', width: 140),
    const HDataColumn(label: '主要特性', field: 'features', width: 270),
    const HDataColumn(label: '迁移建议', field: 'migration', width: 180),
    const HDataColumn(label: '备注', field: 'notes'),
  ];
  
  // 保存编辑中的行数据
  Map<String, dynamic>? _editingRow;
  // 编辑行的索引
  int? _editingRowIndex;
  
  // 显示编辑对话框
  void _showEditDialog(Map<String, dynamic> row, int index) {
    // 创建一个副本用于编辑
    _editingRow = Map<String, dynamic>.from(row);
    _editingRowIndex = index;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('编辑行数据'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: _columns.map((column) {
              return Padding(
                padding: const EdgeInsets.only(bottom: 16.0),
                child: TextFormField(
                  initialValue: _editingRow![column.field]?.toString() ?? '',
                  decoration: InputDecoration(
                    labelText: column.label,
                    border: OutlineInputBorder(),
                  ),
                  onChanged: (value) {
                    _editingRow![column.field] = value;
                  },
                ),
              );
            }).toList(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 保存编辑的数据并强制更新
              setState(() {
                if (_editingRowIndex != null && _editingRow != null) {
                  // 创建一个新的列表，以确保Flutter检测到数据变化
                  _editableData[_editingRowIndex!] = Map<String, dynamic>.from(_editingRow!);
                  // 创建一个新的列表引用，确保触发状态更新
                  _editableData = List.from(_editableData);
                }
              });
              Navigator.of(context).pop();
              // 添加延迟刷新，确保UI更新
              Future.delayed(Duration.zero, () => setState(() {}));
            },
            child: Text('保存'),
          ),
        ],
      ),
    );
  }

  // 添加行到可编辑表格
  void _addRow() {
    final newRow = {
      'engine': 'New Engine',
      'platform': '平台',
      'architecture': '架构',
      'version': '版本号',
      'performance': 'C',
      'status': '开发中',
      'api': '图形API',
      'features': '主要特性',
      'migration': '迁移建议',
      'notes': '补充说明',
    };
    
    setState(() {
      _editableData.add(newRow);
      // 创建一个新的列表引用，确保触发状态更新
      _editableData = List.from(_editableData);
    });
    
    // 添加后立即显示编辑对话框
    _showEditDialog(newRow, _editableData.length - 1);
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    
    return Container(
      padding: EdgeInsets.only(top: theme.dimens.spacingM),
      color: theme.colors.background, // 灰色背景，与原HTML页面一致
      // 使用Column和Expanded替代SingleChildScrollView
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: _buildTableCard(
              theme: theme,
              title: '可编辑表格',
              subtitle: '增删改查',
              content: HDataTable(
                columns: _columns,
                data: _editableData,
                showBorder: true,
                showStripes: true,
                showHover: true,
                enablePagination: true,
                enableSearch: true,
                leftActions: [
                  // 添加行按钮，放置在表格头部左侧
                  ElevatedButton(
                    onPressed: _addRow,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: theme.colors.primary,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    ),
                    child: const Text('添加行'),
                  ),
                  const SizedBox(width: 16), // 加点间距
                ],
                rightActions: [
                  // 刷新按钮，放置在搜索框右侧
                  IconButton(
                    icon: const Icon(Icons.refresh),
                    tooltip: '刷新数据',
                    onPressed: () {
                      // 重置为初始数据
                      setState(() {
                        _editableData = [
                          {'engine': 'Skia', 'platform': 'Android', 'architecture': 'ARM64', 'version': '3.19.0', 'performance': 'A+', 'status': '稳定', 'api': 'OpenGL/Vulkan', 'features': '完全支持Flutter API', 'migration': '无需迁移', 'notes': '默认渲染引擎，性能良好'},
                          {'engine': 'Impeller', 'platform': 'iOS', 'architecture': 'ARM64', 'version': '3.29.0', 'performance': 'A+', 'status': '默认', 'api': 'Metal', 'features': '预编译着色器，无运行时编译', 'migration': '强制使用', 'notes': 'Skia已完全移除，部分API可能需要适配'},
                          {'engine': 'Impeller', 'platform': 'Android', 'architecture': 'ARM64', 'version': '3.29.0', 'performance': 'A+', 'status': '默认', 'api': 'Vulkan', 'features': '预编译着色器，减少内存使用', 'migration': '默认启用', 'notes': '性能有明显提升'},
                        ];
                      });
                    },
                  ),
                  // 导出按钮
                  IconButton(
                    icon: const Icon(Icons.download),
                    tooltip: '导出数据',
                    onPressed: () {
                      // 导出数据的逻辑
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('数据导出成功')),
                      );
                    },
                  ),
                ],
                onRowTap: (row) {
                  // 这里实现编辑功能
                  final index = _editableData.indexWhere((item) => 
                    // 根据数据匹配找到对应行索引
                    item['platform'] == row['platform'] && 
                    item['engine'] == row['engine']);
                  
                  if (index != -1) {
                    _showEditDialog(row, index);
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  /// 构建表格卡片
  Widget _buildTableCard({
    required HTheme theme,
    required String title,
    required Widget content,
    String? subtitle,
    List<Widget>? headerActions,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(0), // 方形卡片，与原HTML页面一致
      ),
      margin: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 卡片标题
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            child: Row(
              children: [
                Text(
                  title,
                  style: theme.textStyles.h3,
                ),
                if (subtitle != null) ...[
                  const SizedBox(width: 8),
                  Text(
                    subtitle,
                    style: theme.textStyles.secondary.copyWith(
                      fontSize: 12,
                    ),
                  ),
                ],

                const SizedBox(width: 16),
                // 头部操作按钮
                if (headerActions != null) ...headerActions,

                const Spacer(),
                // 工具按钮
                _buildToolButton(
                  icon: Icons.keyboard_arrow_up,
                  tooltip: '折叠',
                  onPressed: () {},
                ),
                _buildToolButton(
                  icon: Icons.settings,
                  tooltip: '设置',
                  onPressed: () {},
                ),
                _buildToolButton(
                  icon: Icons.close,
                  tooltip: '关闭',
                  onPressed: () {},
                ),
              ],
            ),
          ),
          
          // 表格内容 - 使用Expanded包裹内容区域
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 16.0, top: 8.0),
              child: content,
            ),
          ),
        ],
      ),
    );
  }
  
  /// 构建工具按钮
  Widget _buildToolButton({
    required IconData icon,
    required String tooltip,
    required VoidCallback onPressed,
  }) {
    return IconButton(
      icon: Icon(icon, size: 18),
      onPressed: onPressed,
      tooltip: tooltip,
      padding: const EdgeInsets.all(8.0),
      constraints: const BoxConstraints(),
      splashRadius: 20,
    );
  }
} 